import config from './config.js'
import login from './login.js'
import msg from './message.js'

function tokenTimeout() {
  let redirectPath = ''
  wx.reLaunch({
    url: '/pages/login/login',
  })
  throw new Error('登录超时，请重新登录。')
}

// 验证是否需要token
function checkPath(path) {
  const index = config.requestExclude.indexOf(path)
  return index < 0
}

// 获取token
async function getToken() {
  const currentTime = parseInt(new Date().getTime() / 1000)
  const expireTime = wx.getStorageSync('expireTime')
  if (currentTime < expireTime) {
    return wx.getStorageSync('token')
  } else {
    try {
      return await getTokenByServer()
    } catch (e) {
      return ''
    }
  }
}

// 从服务器获取token
function getTokenByServer() {
  const openid = wx.getStorageSync('openid')
  return new Promise((resolve, reject) => {
    wx.request({
      url: '',
      data: {
        openid: openid
      },
      header: {
        'Content-Type': 'application/json;charset=utf-8'
      },
      method: 'POST',
      success: res => {
        if (res.statusCode == 200) {
          if (res.data.code === 0) {
            wx.setStorageSync('token', res.data.token)
            wx.setStorageSync('expireTime', res.data.expireTime)
            resolve(res.data)
          } else {
            msg.alert(res.data.msg)
            reject(res.data.msg)
          }
        } else {
          msg.alert(res.statusCode + ', ' + res.errMsg)
          reject(res.statusCode + ', ' + res.errMsg)
        }
      },
      fail: err => {
        if (err.statusCode == 401) {
          quit()
        } else {
          msg.alert(err.errMsg)
          reject(err.errMsg)
        }
      }
    })
  })
}

async function __request(method, uri, headers, params) {
  if (checkPath(uri)) {
    headers.token = await getToken()
  }

  return new Promise((resolve, reject) => {
    wx.request({
      url: config.host + (uri || ""),
      data: params,
      header: headers,
      method: method,
      success: res => {
        if (res.statusCode == 200) {
          if (res.data.code === 0) {
            resolve(res.data)
          } else {
            msg.alert(res.data.msg)
            reject(res.data.msg)
          }
        } else {
          msg.alert(res.statusCode + ', ' + res.errMsg)
          reject(res.statusCode + ', ' + res.errMsg)
        }
      },
      fail: err => {
        if (err.statusCode == 401) {
          quit()
        } else {
          msg.alert(err.errMsg)
          reject(err.errMsg)
        }
      }
    })
  })
}

async function _get(uri, params) {
  let headers = {
    // 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
    'Content-Type': 'application/json;charset=utf-8'
  }
  return __request('GET', uri, headers, params)
}

async function _post(uri, params) {
  let headers = {
    // 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
    'Content-Type': 'application/json;charset=utf-8'
  }
  return __request('GET', uri, headers, params)
}

async function _put(uri, params) {
  let headers = {
    // 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
    'Content-Type': 'application/json;charset=utf-8'
  }
  return __request('PUT', uri, headers, params)
}

async function _delete(uri, params) {
  let headers = {
    // 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
    'Content-Type': 'application/json;charset=utf-8'
  }
  return __request('DELETE', uri, headers, params)
}

// 退出登录
function quit() {
  const openId = wx.getStorageSync('openid')
  wx.clearStorageSync()
  wx.setStorageSync('openid', openId)
  wx.reLaunch({
    url: '/pages/login/login',
  })
}

export default {
  'get': _get,
  'post': _post,
  'put': _put,
  'delete': _delete
}